# !/usr/bin/env python
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import os
import wsgiref.handlers

from google.appengine.api import datastore
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
import django
#from django import http
from django import shortcuts


LANGUAGE_CODE = 'pt-pt'
USE_I18N = True



class SitesModel(db.Model):
    nome	   = db.StringProperty(required=True )
    cliente  = db.StringProperty(required=True)
    local  = db.StringProperty(required=True)
    coordenadas		 = db.GeoPtProperty()

      

	
    def __str__(self):    
	     return '%s' %self.nome
		 
class FuncModel(db.Model):
    nome	   = db.StringProperty(required=True)
    Morada  = db.StringProperty(required=True)
    telemovel  = db.StringProperty(required=True)
    email		 = db.EmailProperty()
    cargo	     = db.StringProperty()
	
    def __str__(self):    
	     return '%s' %self.nome

class IntModel(db.Model):
  data = db.DateTimeProperty(auto_now_add=True)
  site = db.ReferenceProperty(SitesModel)
  descricao = db.StringProperty()
  funcionario = db.ReferenceProperty(FuncModel)
  prioridade = db.StringProperty(default='Media',choices=[      'Alta', 'Media', 'Baixa'])
  situacao = db.StringProperty(default='Pendente',choices=[      'Pendente', 'Em curso', 'Terminado'])
  def __str__(self):    
        return '%s' %self.site

class DetalheModel(db.Model):
    interv = db.ReferenceProperty(IntModel)
    desc = db.StringProperty(required=True )
    qtd  = db.FloatProperty(required=True)
    preco  = db.FloatProperty(required=True)
    total		 = db.FloatProperty()


class DetalheForm(djangoforms.ModelForm):
  class Meta:
    model = DetalheModel 
    exclude = ['interv','total']	
 
  
class IntForm(djangoforms.ModelForm):
  class Meta:
    model = IntModel
	
class SitesForm(djangoforms.ModelForm):
  class Meta:
    model = SitesModel

class FuncForm(djangoforms.ModelForm):
  class Meta:
    model = FuncModel

# Classe para inserir e editar Sites
class edit(webapp.RequestHandler):	
  def post(self):
    user = users.GetCurrentUser()
    admin = users.IsCurrentUserAdmin()		
    site = None
    
    id = self.request.get('id')
    if id:
      site = SitesModel.get(db.Key.from_path(SitesModel.kind(), int(id)))
	
    form = SitesForm(data=self.request.POST or None, instance=site)
    values = {'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),
    'sign_out': users.CreateLogoutURL('/'), 'form': form, 'site': site}

    if not self.request.POST:
      path = os.path.join(os.path.dirname(__file__), "templates/sites.html")
      return self.response.out.write(template.render(path, values))
    
    errors = form.errors
    if not errors:
      try:
        site = form.save(commit=False)
      except ValueError, err:
       errors['__all__'] = unicode(err)
    if errors:
      path = os.path.join(os.path.dirname(__file__), "templates/sites.html")
      return self.response.out.write(template.render(path, values))
    
    site.put()
    sites = db.GqlQuery('SELECT * FROM SitesModel')
    values = {'admin':admin,'sites': sites,'numberSites' : sites.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_sites.html")
    self.response.out.write(template.render(path, values))


	
# Classe para inserir e editar Intervencoes	
class edit_interv(webapp.RequestHandler):	
  def post(self):
    user = users.GetCurrentUser()
    admin = users.IsCurrentUserAdmin()		
    interv = None
    
    id = self.request.get('id')
    if id:
      interv = IntModel.get(db.Key.from_path(IntModel.kind(), int(id)))
	
    form = IntForm(data=self.request.POST or None, instance=interv)

    values = {'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),
    'sign_out': users.CreateLogoutURL('/'), 'form': form, 'interv': interv}

    if not self.request.POST:
      path = os.path.join(os.path.dirname(__file__), "templates/interv.html")
      return self.response.out.write(template.render(path, values))
    
    errors = form.errors
    if not errors:
      try:
        interv = form.save(commit=False)
      except ValueError, err:
       errors['__all__'] = unicode(err)
    if errors:
      path = os.path.join(os.path.dirname(__file__), "templates/interv.html")
      return self.response.out.write(template.render(path, values))
    
    interv.put()
    interv = db.GqlQuery('SELECT * FROM IntModel')
    values = {'admin':admin,'interv': interv,'numberInterv' : interv.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_interv.html")
    self.response.out.write(template.render(path, values))

# Classe para inserir e editar Funcionarios
class edit_func(webapp.RequestHandler):	
  def post(self):
    user = users.GetCurrentUser()
    admin = users.IsCurrentUserAdmin()		
    func = None
    
    id = self.request.get('id')
    if id:
      func = FuncModel.get(db.Key.from_path(FuncModel.kind(), int(id)))
	
    form = FuncForm(data=self.request.POST or None, instance=func)

    values = {'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),
    'sign_out': users.CreateLogoutURL('/'), 'form': form, 'func': func}

    if not self.request.POST:
      path = os.path.join(os.path.dirname(__file__), "templates/func.html")
      return self.response.out.write(template.render(path, values))
    
    errors = form.errors
    if not errors:
      try:
        func = form.save(commit=False)
      except ValueError, err:
       errors['__all__'] = unicode(err)
    if errors:
      path = os.path.join(os.path.dirname(__file__), "templates/func.html")
      return self.response.out.write(template.render(path, values))
    
    func.put()
    func = db.GqlQuery('SELECT * FROM FuncModel')
    values = {'admin':admin,'func': func,'numberFunc' : func.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_func.html")
    self.response.out.write(template.render(path, values))

	
# Classe para inserir e editar detalhes
class edit_detalhe(webapp.RequestHandler):	
  def post(self):
    user = users.GetCurrentUser()
    admin = users.IsCurrentUserAdmin()		
    detalhe = None
    
    id = self.request.get('id')
    id_interv = self.request.get('id_interv')
	
    if id_interv:
      key_interv = IntModel.get(db.Key.from_path(IntModel.kind(), int(id_interv)))
	
    if id:
      detalhe = DetalheModel.get(db.Key.from_path(DetalheModel.kind(), int(id)))
	
    form = DetalheForm(data=self.request.POST or None, instance=detalhe)

    values = {'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),
    'sign_out': users.CreateLogoutURL('/'), 'form': form, 'detalhe': detalhe}

    if not self.request.POST:
      path = os.path.join(os.path.dirname(__file__), "templates/detalhe.html")
      return self.response.out.write(template.render(path, values))
    
    errors = form.errors
    if not errors:
      try:
        detalhe = form.save(commit=False)
      except ValueError, err:
       errors['__all__'] = unicode(err)
    if errors:
      path = os.path.join(os.path.dirname(__file__), "templates/detalhe.html")
      return self.response.out.write(template.render(path, values))
    
    #key = IntModel.get(db.Key.from_path(IntModel.kind(), 416))
    detalhe.interv = key_interv
    detalhe.total = detalhe.qtd * detalhe.preco
    detalhe.put()
    detalhe = db.GqlQuery('SELECT * FROM DetalheModel where interv =:1',key_interv)
	
    tot = 0
    for x in detalhe:
	  tot = tot + float(x.total)
	
    values = {'admin':admin,'tot':tot,'id_interv':id_interv,'detalhe': detalhe,'numberDetalhe' : detalhe.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_detalhe.html")
    self.response.out.write(template.render(path, values))	
	
# Classe para apagar Sites	
class apagar(webapp.RequestHandler):	
  def post(self):
    user = users.get_current_user()
    admin = users.IsCurrentUserAdmin()	
    if user:
      id2 = int(self.request.get('id'))
      todo = SitesModel.get_by_id(id2)
      erro = db.GqlQuery('SELECT * FROM IntModel WHERE site = :1 ',todo)
      if (erro.count() == 0):
	    todo.delete()
      else:
        path = os.path.join(os.path.dirname(__file__), "templates/erro.html")
        return self.response.out.write(template.render(path, {'erro': erro}))
    sites = db.GqlQuery('SELECT * FROM SitesModel')
    values = {'admin':admin,'sites': sites,'numberSites' : sites.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_sites.html")
    self.response.out.write(template.render(path, values))

# Classe para apagar Funcionarios		
class apagar_func(webapp.RequestHandler):	
  def post(self):
    user = users.get_current_user()
    admin = users.IsCurrentUserAdmin()	
    if user:
      id2 = int(self.request.get('id'))
      todo = FuncModel.get_by_id(id2)
      erro = db.GqlQuery('SELECT * FROM IntModel WHERE funcionario = :1 ',todo)
      if (erro.count() == 0):
	    todo.delete()
      else:
        path = os.path.join(os.path.dirname(__file__), "templates/erro.html")
        return self.response.out.write(template.render(path, {'erro': erro}))
    func = db.GqlQuery('SELECT * FROM FuncModel')
    values = {'admin':admin,'func': func,'numberFunc' : func.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_func.html")
    self.response.out.write(template.render(path, values))

# Classe para apagar Intervencoes	
class apagar_interv(webapp.RequestHandler):	
  def post(self):
    user = users.get_current_user()
    admin = users.IsCurrentUserAdmin()
    if user:
      id2 = int(self.request.get('id'))
      todo = IntModel.get_by_id(id2)
      erro = db.GqlQuery('SELECT * FROM DetalheModel WHERE interv = :1 ',todo)
      if (erro.count() == 0):
	    todo.delete()
      else:
        path = os.path.join(os.path.dirname(__file__), "templates/erro2.html")
        return self.response.out.write(template.render(path, {'erro': erro}))
    interv = db.GqlQuery('SELECT * FROM IntModel')
    values = {'admin':admin,'interv': interv,'numberInterv' : interv.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_interv.html")
    self.response.out.write(template.render(path, values))
	
class apagar_detalhe(webapp.RequestHandler):	
  def post(self):
    user = users.get_current_user()
    admin = users.IsCurrentUserAdmin()
    id_interv = int(self.request.get('id_interv'))
    key = IntModel.get(db.Key.from_path(IntModel.kind(), id_interv))

    if user:
      id2 = int(self.request.get('id'))
      todo = DetalheModel.get_by_id(id2)
      todo.delete()
    detalhe = db.GqlQuery('SELECT * FROM DetalheModel where interv =:1',key) 
    tot = 0
    for x in detalhe:
	  tot = tot + float(x.total)
	
    values = {'admin':admin,'tot':tot,'id_interv':id_interv,'detalhe': detalhe,'numberDetalhe' : detalhe.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_detalhe.html")
    self.response.out.write(template.render(path, values))	
	

# Classe para listar Intervencoes
class list_interv(webapp.RequestHandler):
  def get(self):
    user = users.GetCurrentUser()
    admin = users.IsCurrentUserAdmin()
    #pri = "Media"
    #interv = db.GqlQuery('SELECT * FROM IntModel where prioridade = :1   ORDER BY created DESC',pri)
    interv = db.GqlQuery('SELECT * FROM IntModel ')
    values = {'admin':admin,'interv': interv,'numberInterv' : interv.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_interv.html")
    self.response.out.write(template.render(path, values))	

# Classe para listar detalhes
class list_detalhe_interv(webapp.RequestHandler):
  def post(self):
    user = users.GetCurrentUser()
    admin = users.IsCurrentUserAdmin()
    id = int(self.request.get('id'))
    key = IntModel.get(db.Key.from_path(IntModel.kind(), int(id)))
    #pri = "adas"
    detalhe = db.GqlQuery('SELECT * FROM DetalheModel where interv = :1   ',key)

    tot = 0
    for x in detalhe:
	  tot = tot + float(x.total)
	
	#detalhe = db.GqlQuery('SELECT * FROM DetalheModel ')
    values = {'admin':admin,'tot':tot,'id_interv':id,'detalhe': detalhe,'numberDetalhe' : detalhe.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_detalhe.html")
    self.response.out.write(template.render(path, values))	

	
# Classe para listar Funcionarios	
class list_func(webapp.RequestHandler):
  def get(self):
    user = users.GetCurrentUser()
    admin = users.IsCurrentUserAdmin()
    func = db.GqlQuery('SELECT * FROM FuncModel ')
    values = {'admin':admin,'func': func,'numberFunc' : func.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_func.html")
    self.response.out.write(template.render(path, values))	
	
# Classe para listar Sites
class list_site(webapp.RequestHandler):
  def get(self):
    user = users.GetCurrentUser()
    admin = users.IsCurrentUserAdmin()
    sites = db.GqlQuery('SELECT * FROM SitesModel')
    values = {'admin':admin,'sites': sites,'numberSites' : sites.count(),'user': user, 'sign_in': users.CreateLoginURL(self.request.uri),'sign_out': users.CreateLogoutURL('/'), }
    path = os.path.join(os.path.dirname(__file__), "templates/list_sites.html")
    self.response.out.write(template.render(path, values))
	


def main():
  application = webapp.WSGIApplication([
    ('/', list_site),
	('/sites', list_site),
	('/interv', list_interv),
	('/detalhe_interv', list_detalhe_interv),	
	('/func', list_func),
	('/edit', edit),
	('/edit_interv', edit_interv),
	('/edit_func', edit_func),	
	('/edit_detalhe', edit_detalhe),		
	('/apagar', apagar),
	('/apagar_interv', apagar_interv),
	('/apagar_func', apagar_func),	
	('/apagar_detalhe', apagar_detalhe),		
    ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
